/**
 * Create in 2012-11-1 上午4:33:41.
 */
package kit4j.app.notepad.ui.comp;

import java.awt.Container;
import java.awt.Cursor;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.Icon;
import javax.swing.JLabel;

/**
 * 
 * @author MiniKnife
 * 
 */
public class ResizeWindowLabel extends JLabel {

	private static final long serialVersionUID = 4506977724818039476L;
	
	private MouseAdapter mouseAdapter;

	/**
	 * 
	 */
	public ResizeWindowLabel() {
		init();
	}

	/**
	 * @param text
	 */
	public ResizeWindowLabel(String text) {
		super(text);
		init();
	}

	/**
	 * @param image
	 */
	public ResizeWindowLabel(Icon image) {
		super(image);
		init();
	}

	/**
	 * @param text
	 * @param horizontalAlignment
	 */
	public ResizeWindowLabel(String text, int horizontalAlignment) {
		super(text, horizontalAlignment);
		init();
	}

	/**
	 * @param image
	 * @param horizontalAlignment
	 */
	public ResizeWindowLabel(Icon image, int horizontalAlignment) {
		super(image, horizontalAlignment);
		init();
	}

	/**
	 * @param text
	 * @param icon
	 * @param horizontalAlignment
	 */
	public ResizeWindowLabel(String text, Icon icon, int horizontalAlignment) {
		super(text, icon, horizontalAlignment);
		init();
	}

	private void init() {
		mouseAdapter = new MouseAdapter() {

			private int pressX;
			private int pressY;
			private int pressWidth;
			private int pressHeight;
			
			/**
			 * @see java.awt.event.MouseAdapter#mouseExited(java.awt.event.MouseEvent)
			 */
			@Override
			public void mouseExited(MouseEvent e) {
				Window window = getWindow();
				window.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
			}
			
			/**
			 * @see java.awt.event.MouseAdapter#mouseEntered(java.awt.event.MouseEvent)
			 */
			@Override
			public void mouseEntered(MouseEvent e) {
				Window window = getWindow();
				window.setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
			}

			@Override
			public void mousePressed(MouseEvent e) {
				Window window = getWindow();
				pressX = e.getXOnScreen();
				pressY = e.getYOnScreen();
				pressWidth = window.getWidth();
				pressHeight = window.getHeight();
			}

			@Override
			public void mouseDragged(MouseEvent e) {
				Window window = getWindow();
				int dX = e.getXOnScreen() - pressX;
				int dY = e.getYOnScreen() - pressY;

				window.setSize(pressWidth + dX, pressHeight + dY);
			}
		};

		addMouseListener(mouseAdapter);
		addMouseMotionListener(mouseAdapter);
	}

	public Window getWindow() {
		Container parent = getParent();

		while (parent != null) {
			if (parent instanceof Window) {
				return (Window) parent;
			} else {
				parent = parent.getParent();
			}
		}
		
		return null;
	}

}
